package cn.gov.chinamor.zxing.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

public class HttpUtil {

	public static String crawlUrl(String url) throws Exception {
		
	    HttpEntity entity = getEntity(url, "a=1");
	    BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
	    StringBuffer sb = new StringBuffer();
	    String line = null;
	    while ((line = br.readLine()) != null) {
	    	sb.append(line);
	    }
	    return sb.toString();
	}
	
	private static HttpEntity getEntity(String url, String content) throws Exception {
		final int timeOut = 20000;
		HttpPost httpPost = new HttpPost(url);
		StringEntity se = new StringEntity(content, HTTP.UTF_8);
		httpPost.setEntity(se);

		HttpParams httpParameters = new BasicHttpParams();
		// Set the timeout in milliseconds until a connection is established.
		int timeoutConnection = timeOut;
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
		// Set the default socket timeout (SO_TIMEOUT) 
		// in milliseconds which is the timeout for waiting for data.
		int timeoutSocket = timeOut;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

		DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
		BasicHttpResponse httpResponse = (BasicHttpResponse)  httpClient.execute(httpPost);

		HttpEntity entity = httpResponse.getEntity();
		return entity;
	}
}